package com.hopu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hopu.domain.Role;
import com.hopu.domain.User;
import com.hopu.result.ResponseEntity;
import com.hopu.service.IUserService;
import com.hopu.utils.ShiroUtils;
import com.hopu.utils.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

import static com.hopu.result.ResponseEntity.success;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

//    向用户列表页面跳转
    @RequiresPermissions("user:list")
    @RequestMapping("/toListPage")
    public String userList(){
        return "admin/user/user_list";
    }

    /**
     *多条件分页查询用户列表信息，根据用户名username、电话tel、邮箱email模糊查询
     */
    @RequestMapping("/list")
    @ResponseBody
    @RequiresPermissions("user:list")
     public IPage<User> findByPage(@RequestParam(value = "page",defaultValue = "1") int page,
                                   @RequestParam(value = "limit",defaultValue = "5") int limit,
                                   User user){
        Page<User> page2 = new Page<User>(page,limit);
        QueryWrapper<User> queryWrapper =new QueryWrapper<>(new User());
        if (user !=null){
            if (!StringUtils.isEmpty(user.getUserName())){
                queryWrapper.like("user_name",user.getUserName());
            }if (!StringUtils.isEmpty(user.getTel())){
                queryWrapper.like("tel",user.getTel());
            }if (!StringUtils.isEmpty(user.getEmail())){
                queryWrapper.like("email",user.getEmail());
            }
        }
        IPage<User> userIPage =userService.page(page2,queryWrapper);
        return userIPage;
     }

//向用户添加页面跳转
    @RequiresPermissions("user:add")
    @RequestMapping("/toAddPage")
     public String toAddPage(){
        return "admin/user/user_add";
     }
    /**
     * 保存
     *
     */
    @ResponseBody
    @RequestMapping("/addUser")
    @RequiresPermissions("user:add")
    public ResponseEntity addUser(User user,HttpServletRequest request)throws IOException{
        // 可以先对用户名重名校验
        // 创建条件查询封装对象
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",user.getUserName());
        User one = userService.getOne(queryWrapper);

        if(one !=null){
            return ResponseEntity.error("用户名已经存在了");
        }
        String fileName =(String)request.getSession().getAttribute("fileName");
        user.setUserImg(fileName);
        // 开始添加用户
        user.setId(UUIDUtils.getID());
        user.setSalt(UUIDUtils.getID());
        user.setCreateTime(new Date());
        // 对新用户密码进行加密处理
        ShiroUtils.encPass(user);
        userService.save(user);
        return success();
    }

//    向用户修改页面跳转
    @RequestMapping("/toUpdatePage")
    @RequiresPermissions("user:update")
    public String toUpdatePage(String id, Model model){
        User user = userService.getById(id);
        model.addAttribute("user", user);
        return "admin/user/user_update";
    }

/**
 * 修改
 */
    @ResponseBody
    @RequestMapping("/updateUser")
    @RequiresPermissions("user:update")
    public ResponseEntity updateUser(User user){
        user.setUpdateTime(new Date());
        ShiroUtils.encPass(user);
        userService.updateById(user);
        return success();
    }

/**
 * 删除（支持批量删除）
 */
    @ResponseBody
    @RequestMapping("/delete")
    @RequiresPermissions("user:delete")
    public ResponseEntity delete(@RequestBody ArrayList<User> users){
        try {
            List<String> list = new ArrayList<String>();
            // 如果是root用户，禁止删除
            for (User user : users) {
                if("root".equals(user.getUserName())){
                    throw new Exception("不能删除超级管理员");
                }
                list.add(user.getId());
            }
            userService.removeByIds(list);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.error(e.getMessage());
        }
        return success();
    }

    /**
     * 用户角色权限分配
     *
     * 1.跳转分配角色页面
     */
    // 跳转到用户角色分配页面
    @RequestMapping("/toSetUserRole")
    @RequiresPermissions("user:setRole")
    public String toSetUserRole(@RequestParam(value = "id") String userId, HttpServletRequest request){
        request.setAttribute("userId",userId);
        return "admin/user/user_setRole";
    }

    /**
     * 设置角色
     */
    @RequestMapping("/setRole")
    @ResponseBody
    @RequiresPermissions("user:setRole")
    public ResponseEntity setRole(String userId,@RequestBody List<Role> roles){
        userService.setRole(userId,roles);
        return success();
    }

    @ResponseBody
    @RequestMapping("/upLoadImg")
    public ResponseEntity upLoadImg(@RequestParam("file") MultipartFile userImg,HttpServletRequest request){
        File file = new File("/root/nginx/www");
        String newFileName = UUID.randomUUID() + userImg.getOriginalFilename();
        try {
            userImg.transferTo(new File(file,newFileName));
        }catch (IOException e){
            e.printStackTrace();
        }
        request.getSession().setAttribute("fileName",newFileName);

        HashMap<String,String>map =new HashMap<>();
        map.put("src","/root/nginx/www/"+newFileName);
        return ResponseEntity.success("头像上传成功",map);
    }

}